package com.snails.app.base.mvp.model;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.snails.app.base.mvp.presenter.AbstractPresenter;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * @author lawrence
 * @date 2019-04-28 22:27
 */
public abstract class BaseModel<P extends AbstractPresenter>
        implements AbstractModel<P> {

    @Nullable protected P mPresenter = null;
    // 取消RxJava执行
    private CompositeDisposable mCompositeDisposable;
    private Object mLockObj = new Object();

    @Override
    public void onAttachP(P presenter) {
        this.mPresenter = presenter;
    }

    /**
     * 回收资源，取消网络请求。
     * 此方法在activity/fragment销毁时触发
     */
    @Override
    public void onDetach() {
        if (mCompositeDisposable != null) mCompositeDisposable.clear();
    }

    protected void addSubscribe(Disposable disposable) {
        if (mCompositeDisposable == null) {
            synchronized (mLockObj) {
                if (mCompositeDisposable == null) {
                    mCompositeDisposable = new CompositeDisposable();
                }
            }
        }
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void onCompleted(@Nullable Bundle bundle) {
        if (this.mPresenter != null) {
            this.mPresenter.onCompleted(bundle);
        }
    }

    @Override
    public void showLoading(String message) {
        if (this.mPresenter != null) {
            this.mPresenter.showLoading(message);
        }
    }

    @Override
    public void showLoading() {
        if (this.mPresenter != null) {
            this.mPresenter.showLoading();
        }
    }

    @Override
    public void closeLoading() {
        if (this.mPresenter != null) {
            this.mPresenter.closeLoading();
        }
    }

    @Override
    public void showToast(@StringRes int resId) {
        if (this.mPresenter != null) {
            this.mPresenter.showToast(resId);
        }
    }

    @Override
    public void showToast(String message) {
        if (this.mPresenter != null) {
            this.mPresenter.showToast(message);
        }
    }

}
